<?php

class ConfessionController extends BaseAdminController {

    public $menu = array(
        array('label' => 'Create new article', 'url' => array('confession/create')),
        array('label' => 'List all articlees', 'url' => array('confession/index'))
    );

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('create', 'saveCreate', 'update', 'index', 'delete', 'deleteImage', 'list', 'show', 'content', 'images', 'search'),
                'users' => array('admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $this->redirect(array('list'));
    }

    /**
     * List all search
     */
    public function actionSearch() {
        $confessionSearch = new Search;
        if (isset($_GET['Search'])) {
            $confessionSearch->attributes = $_GET['Search'];
            $keyWord = $confessionSearch->keyWord;
            $criteria = new CDbCriteria;
            $criteria->distinct = true;
            $criteria->order = 'postdate DESC';

            //continue with search condition
            $searchCondition = '';
            if (strlen($keyWord) > 0) {
                if ($confessionSearch->searchByContent) {
                    if ($searchCondition == '') {
                        $searchCondition = 'content like :keyWord';
                    } else {
                        $searchCondition = ' OR content like :keyWord';
                    }
                }
                if (!$confessionSearch->searchByContent) {
                    $searchCondition = 'content like :keyWord';
                }
            }
            $criteria->addCondition($searchCondition);
            $criteria->params = array(':keyWord' => '%' . $keyWord . '%');
            $dataProvider = new CActiveDataProvider('Confession', array(
                'criteria' => $criteria,
                'pagination' => array(
                    'pageSize' => Constant::ADMIN_NUMBER_NEW_PER_PAGE,
                ),
            ));
            $articleSearch = new Search;
            $this->render('list', array(
                'confessionSearch' => $confessionSearch,
                'dataProvider' => $dataProvider,
            ));
        }
    }

    /**
     * Manages all models.
     */
    public function actionList() {
        $confessionSearch = new Search;
        $criteria = new CDbCriteria;
        $criteria->order = 'postdate DESC';

        $dataProvider = new CActiveDataProvider('Confession', array(
            'criteria' => $criteria,
            'pagination' => array(
                'pageSize' => Constant::ADMIN_NUMBER_NEW_PER_PAGE,
            ),
        ));
        $this->render('list', array(
            'confessionSearch' => $confessionSearch,
            'dataProvider' => $dataProvider,
        ));
    }

    public function renameImage($imageName) {
        $newName = str_replace(array(' ', '\\', '/', ',', '(', ')', '-', '"', '\'', '%'), '_', $imageName);
        $newName = time() . '_' . $newName;
        return $newName;
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $confession = new Confession;
        $confession->year = date('Y');
        $confession->name = 'admin';
        $message = ''; //store message;
        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($confession);

        if (isset($_POST['Confession'])) {
            $confession->attributes = $_POST['Confession'];
            try {
                if ($confession->save()) {
                    Yii::app()->user->setFlash('message', Yii::t('article', 'successCreate'));
                    $this->refresh();
                    $this->redirect(array('create'));
                }
            } catch (Exception $ex) {
                echo $ex->getMessage();
                Yii::app()->user->setFlash('message', Yii::t('article', 'failCreate'));
                $this->redirect(array('create'));
            }
            $message = Yii::t('article', 'failCreate');
        }

        $this->render('create', array(
            'message' => $message,
            'confession' => $confession,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $confession = $this->loadModel($id);
        $message = ''; //store message;
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($product);

        if (isset($_POST['Confession'])) {
            $confession->attributes = $_POST['Confession'];
            try {
                if ($confession->save()) {
                    Yii::app()->user->setFlash('message', Yii::t('article', 'successUpdate'));
                    $this->redirect(array('list'));
                }
            } catch (Exception $ex) {
                echo $ex->getMessage();
                Yii::app()->user->setFlash('message', Yii::t('article', 'failUpdate'));
                $this->redirect(array('list'));
            }
            $message = Yii::t('article', 'failCreate');
        }

        $this->render('update', array(
            'message' => $message,
            'confession' => $confession,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $confession = $this->loadModel($id);
            $confession->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, Yii::t('default', 'notValidWeb'));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $confession = Confession::model()->findByPk($id);
        if ($confession === null)
            throw new CHttpException(404, Yii::t('default', 'notExistWeb'));
        return $confession;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($product) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'article-form') {
            echo CActiveForm::validate($product);
            Yii::app()->end();
        }
    }

    /**
     * show image by path
     */
    public function actionShow($path) {
        $imagePath = $path;
        Yii::app()->clientScript->scriptMap['jquery.js'] = false;
        $this->renderPartial('viewImage', array('imagePath' => $imagePath,), false, true);
    }

    /**
     * action Content
     */
    public function actionContent($id) {//Yii::app()->createUrl(\'product/content\',array(\'id\'=>$data->id)
        $confession = Confession::model()->findByPk($id);
        $this->renderPartial('showContent', array('confession' => $confession,), false, true);
    }

    /**
     * action Images
     */
    public function actionImages($id) {
        $product = Product::model()->findByPk($id);
        $productImages = $product->productImages;
        Yii::app()->clientScript->scriptMap['jquery.js'] = false;
        $this->renderPartial('showImages', array('productImages' => $productImages,), false, true);
    }

    /**
     * delete image update
     */
    public function actionDeleteImage($id) {
        $productImage = ProductImage::model()->findByPk($id);
        $productImage->delete();
        // die;
    }

}
